package com.hui.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hui.server.entity.Employee;
import com.hui.server.entity.MailConstants;
import com.hui.server.entity.MailLog;
import com.hui.server.mapper.EmployeeMapper;
import com.hui.server.mapper.MailLogMapper;
import com.hui.server.service.EmployeeService;
import com.hui.server.util.RespPageBean;
import com.hui.server.util.Result;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hui
 * @since 2022-03-31
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {


    private final EmployeeMapper employeeMapper;

    private final RabbitTemplate rabbitTemplate;

    private final MailLogMapper mailLogMapper;

    @Autowired
    public EmployeeServiceImpl(EmployeeMapper employeeMapper, RabbitTemplate rabbitTemplate, MailLogMapper mailLogMapper) {
        this.mailLogMapper = mailLogMapper;
        this.rabbitTemplate = rabbitTemplate;
        this.employeeMapper = employeeMapper;
    }

    /**
     * 分页查询所有员工，并且按照指定条件查询
     *
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public RespPageBean getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {

        Page<Employee> page = new Page<>(currentPage, size);

//        int size1 = employeeMapper.getAllEmployeeOrOneById(null).size();//查询全部，返回前端有bug

        IPage<Employee> employeeIPage = employeeMapper.getEmployeeByPage(page, employee, beginDateScope);

        RespPageBean respPageBean = new RespPageBean(employeeIPage.getTotal(), employeeIPage.getRecords());
        return respPageBean;
    }


    /**
     * 返回数据库中最大工号再加一，用于新增员工
     *
     * @return
     */
    @Override
    public Result<?> maxWorkId() {

        List<Map<String, Object>> list = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        String s = String.format("%08d", Integer.parseInt(list.get(0).get("max(workID)").toString()) + 1);
        return Result.success(s);
    }

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @Override
    public Result<?> insertEmployee(Employee employee) {
        LocalDate beginDate = employee.getBeginContract();
        LocalDate EndDate = employee.getEndContract();

        //先按天获取，再转为年
        long days = beginDate.until(EndDate, ChronoUnit.DAYS);

        //# 代表一个数字，0代表位数不足以0补充
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365.00)));

        int insert = employeeMapper.insert(employee);

        if (1 == insert) {
            Employee emp = employeeMapper.getAllEmployeeOrOneById(employee.getId()).get(0);
            //数据库记录发送的消息
            String msgId = UUID.randomUUID().toString();
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(emp.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setCount(0);
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogMapper.insert(mailLog);
            //发送信息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME, emp, new CorrelationData(msgId));
            return Result.success("插入成功！");
        }

        return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "插入失败！");


    }


    /**
     * 传入id如果存在，则按id查员工，否则查所有；需要对应填充员工employee表的其他表字段（主要是其他的表字段太多）
     *
     * @param
     * @return
     */
    @Override
    public List<Employee> getAllEmployeeOrOneById(Integer id) {
        return id == -1 ?
                employeeMapper.getAllEmployeeOrOneById(null) :
                employeeMapper.getAllEmployeeOrOneById(id);
    }

    /**
     * 获取员工、员工的套账信息，带部门信息
     *
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public RespPageBean getEmployeeWithSalary(Integer currentPage, Integer size) {
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> list = employeeMapper.getEmployeeAndSalaryAndDepByPage(page);
        RespPageBean pageBean = new RespPageBean(list.getTotal(),list.getRecords());
        return pageBean;
    }
}
